package com.laundry.controller;

import com.laundry.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/test")
@RequiredArgsConstructor
public class DatabaseTestController {
    
    private final DataSource dataSource;
    private final JdbcTemplate jdbcTemplate;
    
    @GetMapping("/db-info")
    public ApiResponse<Map<String, Object>> getDatabaseInfo() {
        try {
            Map<String, Object> info = new HashMap<>();
            
            try (Connection connection = dataSource.getConnection()) {
                DatabaseMetaData metaData = connection.getMetaData();
                info.put("databaseProductName", metaData.getDatabaseProductName());
                info.put("databaseProductVersion", metaData.getDatabaseProductVersion());
                info.put("url", metaData.getURL());
                info.put("userName", metaData.getUserName());
            }
            
            // 测试查询
            List<Map<String, Object>> tables = jdbcTemplate.queryForList(
                "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PUBLIC'"
            );
            info.put("tables", tables);
            
            // 测试数据
            Long userCount = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM USERS", Long.class);
            info.put("userCount", userCount);
            
            Long categoryCount = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM SERVICE_CATEGORIES", Long.class);
            info.put("categoryCount", categoryCount);
            
            return ApiResponse.success("数据库连接正常", info);
        } catch (Exception e) {
            return ApiResponse.error("数据库连接失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/tables")
    public ApiResponse<List<Map<String, Object>>> getTables() {
        try {
            List<Map<String, Object>> tables = jdbcTemplate.queryForList(
                "SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PUBLIC' ORDER BY TABLE_NAME"
            );
            return ApiResponse.success(tables);
        } catch (Exception e) {
            return ApiResponse.error("获取表信息失败: " + e.getMessage());
        }
    }
}
